<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入部门名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container tree-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <!-- <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="80px">
            <el-form-item label="关键字" prop="keywords">
                <el-input
                    v-model="queryParams.keywords"
                    placeholder="请输入姓名/手机号"
                    clearable
                    style="width: 240px"
                     @keyup.enter.native="handleQuery"
                    size="small"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form> -->

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['11510']"
              @click="handleAdd"
              >添加部门</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              v-hasPermi="['11550']"
              @click="handleImport"
              >导入部门</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <el-table-column
            label="部门编码"
            prop="deptCode"
            align="left"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门名称"
            prop="deptName"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="人数" prop="peopleNum" align="center" />
          <el-table-column
            label="上级部门"
            prop="dept"
            align="center"
          ></el-table-column>
          <el-table-column
            label="层级"
            prop="hierarchy"
            align="center"
          ></el-table-column>
          <el-table-column label="状态" align="center" key="enable" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="位置排序"
            prop="sort"
            align="center"
            width="100"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['11520']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['11530']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="500px"
          append-to-body
        >
          <!-- 上级部门（自动显示）、*部门编码（长度2位）、*部门名称、层级（下拉框）、顺序号（默认：0） -->
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            :validate-on-rule-change="false"
            label-width="80px"
          >
            <el-form-item label="上级部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="treeOptions"
                :show-count="true"
                placeholder="请选择上级类别"
                @select="selectTree"
              />
            </el-form-item>
            <el-form-item label="部门编码" prop="currDeptCode">
              <el-input
                v-model="form.currDeptCode"
                placeholder="请输入部门编码（长度2位）"
                :disabled="isdeptcode"
                maxlength="2"
                show-word-limit
                @change="getcudept"
              />
              <p class="bianma" v-if="isdepid">部门编码（长度2位）</p>
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
            <el-form-item label="层级" prop="postId">
              <el-select
                v-model="form.hierarchyId"
                placeholder="请选择"
                @change="changeHier"
              >
                <el-option
                  v-for="item in hierOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="位置排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog
          :title="upload.title"
          :visible.sync="upload.open"
          width="400px"
          append-to-body
        >
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-button
                type="warning"
                plain
                size="mini"
                @click="importTemplate"
                >下载模板</el-button
              >
            </div>
            <div class="el-upload__tip" style="color: red" slot="tip">
              提示：仅允许导入“xls”或“xlsx”格式文件！
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getDepartment } from "@/api/select";

import {
  getPage,
  listData,
  getData,
  delData,
  addData,
  updateData,
  EnableStaff,
  exportData,
} from "@/api/system/organize";
import { getDict } from "@/api/select";
export default {
  name: "organize",
  components: { Treeselect },
  data() {
    return {
      isdeptcode: false,
      treeName: undefined,
      treeOptions: [],
      currentId: null,
      currpathIds: "",
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      isdepid: false,
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        ascriptionId: undefined,
        dictId: undefined,
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        deptCode: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          { min: 2, max: 2, message: "长度2位", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: "",
      },
      hierOptions: [], //部门层级
      currdeptIdCode: "", //当前上级部门对应编码
    };
  },
  watch: {
    // 根据名称筛选部门树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getDepartment();
    this.getSelectDict(); //获取数据字典  31-部门层级
  },
  methods: {
    // 部门编码
    getcudept() {
      if (this.form.currDeptCode.length == 1) {
        this.isdepid = true;
      }
    },
    getDepartment() {
      getDepartment().then((response) => {
        this.treeOptions = response.result.data;
        console.log(this.treeOptions);
        if (this.currentId === null) {
          //首次进入当前页面
          this.currentId = response.result.data[0].id; //将节点id赋值给上级id
          console.log("this.currentId", this.currentId);
          this.currdeptIdCode = response.result.data[0].code;
          this.currpathIds = response.result.data[0].pathIds;
          console.log("this.currdeptIdCode1", this.currpathIds);
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        this.getList();
      });
    },
    getList() {
      this.loading = true;
      this.queryParams.dictId = this.currentId;
      listData(this.queryParams).then((response) => {
        console.log("this.queryParams", response);
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    getSelectDict() {
      let tid = 31,
        platform = 0;
      getDict(tid, platform).then((response) => {
        this.hierOptions = response.result.data; //31-部门层级
      });
    },
    handleNodeClick(data) {
      console.log("data", data);
      this.currentId = data.id; //id
      this.currdeptIdCode = data.code;
      this.currpathIds = data.pathIds;
      console.log("节点", this.currpathIds);
      console.log("this.currdeptIdCode", this.currdeptIdCode);
      // this.defaultExpandkeys[0] = this.currentId;   //下一次获取树，默认展开的节点
      this.getList();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
      this.isdepid = false;
      this.isdeptcode = false;
    },
    handleUpdate(row) {
      this.reset();
      this.isdeptcode = true;
      const theId = row.theid || this.ids;
      getData(theId).then((response) => {
        this.form = response.result;
        this.open = true;
        this.title = "修改";
        const str = response.result.deptCode;
        this.form.currDeptCode = str.substring(str.length - 2, str.length);
        console.log(this.form.currDeptCode);
      });
    },
    submitForm() {
      // 给完整编码赋值
      // 完整编码 = 上级编码 + 当前编码

      if (this.form.currDeptCode) {
        // this.form.deptCode = "";
        this.form.deptCode = this.currdeptIdCode + this.form.currDeptCode;
      } else {
        this.form.deptCode = "";
      }

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
              this.getDepartment();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              // this.getList();
              this.getDepartment();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        tid: this.currentId,
        deptId: this.currentId,
        deptCode: undefined, //部门编码（完整）
        currDeptCode: undefined, //当前部门编码（2位）
        deptName: undefined,
        hierarchyId: undefined,
        hierarchy: undefined,
        pathIds: this.currpathIds,
        sort: 0,
      };
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.theid || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          // this.getList();
          this.getDepartment();
          this.msgSuccess("删除成功");
        });
    },
    handleStatusChange(row) {
      console.log("row--", row);
      let text = row.enable === 1 ? "启用" : "停用";
      this.$confirm('是否确认' + text + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口 改变状态值
          return EnableStaff(row.theid, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          console.log('catch----row.enable',row.enable)
          row.enable = row.enable === 0 ? 1 : 0;
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      /* importTemplate().then(response => {
          this.download(response.msg);
        }); */
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口导出表
          // return exportRole(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    changeHier(val) {
      if (this.hierOptions.length > 0) {
        this.form.hierarchy = val
          ? this.hierOptions.find((ele) => ele.id === val).label
          : "";
      }
    },
    selectTree(val) {
      if (this.treeOptions.length > 0) {
        // 获取上级部门（form.deptId）对应的部门编码
        // 上级编码 val.code 待后端添加
        this.currdeptIdCode = val.code;
      }
    },
  },
};
</script>

<style scoped lang="scss">
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
.bianma {
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: -4.2vh;
}
</style>